package com.topisv.tms.rest.qimen.qmservice;

import java.io.StringReader;
import java.io.StringWriter;

import javax.xml.bind.JAXB;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.topisv.tms.entity.EdiGoodsSku;
import com.topisv.tms.exception.PaiUException;
import com.topisv.tms.exception.QMErrorCode;
import com.topisv.tms.rest.qimen.qmentity.request.goodsinfo.EdiGoodsSkuVo;
import com.topisv.tms.rest.qimen.qmentity.request.goodsinfo.GoodsActionType;
import com.topisv.tms.rest.qimen.qmentity.request.goodsinfo.SingleGoodsInfo;
import com.topisv.tms.rest.qimen.qmentity.response.ResponseFlagType;
import com.topisv.tms.rest.qimen.qmentity.response.goodsinfo.GoodsInfoSyncResponse;
import com.topisv.tms.rest.qimen.request.RequestParams;
import com.topisv.tms.rest.qimen.response.ResponseParams;
import com.topisv.tms.rest.qimen.util.goodsinfo.TransferHelper;
import com.topisv.tms.rest.qimen.util.validator.ValidatorUtil;
import com.topisv.tms.service.EdiGoodsSkuService;
import com.topisv.tms.service.base.BaseService;

@Component
public class SingleGoodsInfoSyncService extends BaseService {
    
    @Autowired
    private EdiGoodsSkuService ediGoodsSkuService;
    
    @Transactional(readOnly = false, rollbackFor = Exception.class)
    public ResponseParams execute(RequestParams params)
        throws PaiUException
    {
        SingleGoodsInfo singleGoodsInfo = JAXB.unmarshal(new StringReader(params.getRequestXml()), SingleGoodsInfo.class);
        // 报文校验
        String reqValidatorMsg = ValidatorUtil.qmXmlValidator(singleGoodsInfo);
        if (!ValidatorUtil.SUCCESS_CODE.equals(reqValidatorMsg)) {
            ResponseParams response = new ResponseParams();
            response.setResponseXml(reqValidatorMsg.toString());
            return response;
        }
        
        EdiGoodsSku ediGoodsSku = null;
        if (StringUtils.isBlank(singleGoodsInfo.getItem().getItemId()) && GoodsActionType.ADD.getType().equals(singleGoodsInfo.getActionType())) {
            ediGoodsSku = ediGoodsSkuService.findByCustomerCodeAndSku(singleGoodsInfo.getOwnerCode(), singleGoodsInfo.getItem().getBarCode());
        } else {
            ediGoodsSku = ediGoodsSkuService.loadById(Long.valueOf(singleGoodsInfo.getItem().getItemId()));
        }
        
        if (GoodsActionType.UPDATE.getType().equals(singleGoodsInfo.getActionType())) {
            if (ediGoodsSku == null) {
                throw new PaiUException(QMErrorCode.SKU_NOT_EXISTS, new String[] {singleGoodsInfo.getItem().getBarCode()});
            }
        } else if (!GoodsActionType.ADD.getType().equals(singleGoodsInfo.getActionType())) {
            throw new PaiUException(QMErrorCode.NOT_SUPPORT_METHOD, new String[] {singleGoodsInfo.getActionType()});
        }
        
        // add by yuansheng 546 对爱德朗商品sku_bar重复校验
        if ("ADL".equals(singleGoodsInfo.getOwnerCode())) {
            if (GoodsActionType.ADD.getType().equals(singleGoodsInfo.getActionType())) {
                EdiGoodsSku egs = ediGoodsSkuService.findByCustomerCodeAndBar(singleGoodsInfo.getOwnerCode(), singleGoodsInfo.getItem().getItemCode());
                if (egs != null) {
                    throw new PaiUException(QMErrorCode.SKU_EXISTS, new String[] {singleGoodsInfo.getItem().getItemCode()});
                }
            }
        	if (GoodsActionType.UPDATE.getType().equals(singleGoodsInfo.getActionType())) {
        	    // TODO
        	    EdiGoodsSku egs = ediGoodsSkuService.findByCustomerCodeAndBar(singleGoodsInfo.getOwnerCode(), singleGoodsInfo.getItem().getItemCode());
        	    if (egs != null && !(egs.getId() == Long.valueOf(singleGoodsInfo.getItem().getItemId()))) {
        	        // 根据bar和商家编码查找
        	        // 1.如果找到且ID不同，那么不能更新
        	        // 2.如果找到ID相同，那么为同一条数据的更新，可以更新
        	        throw new PaiUException(QMErrorCode.SKU_EXISTS, new String[] {singleGoodsInfo.getItem().getItemCode()});
                }
            }
        }
        // add by yuansheng 546
        
        EdiGoodsSkuVo skuVo = TransferHelper.toEdiGoodsSku(singleGoodsInfo, ediGoodsSku);
        /*
         * else if
         * (GoodsActionType.DELETE.getType().equals(singleGoodsInfo.getActionType
         * ())) { ediGoodsSkuService.delete(skuVo.getGoodsSku()); }
         */
        
        ediGoodsSku = ediGoodsSkuService.save(skuVo.getGoodsSku());
        // 返回结果
        ResponseParams response = new ResponseParams();
        GoodsInfoSyncResponse goodsInfoSyncResponse = new GoodsInfoSyncResponse();
        goodsInfoSyncResponse.setFlag(ResponseFlagType.SUCCESS.getType());
        goodsInfoSyncResponse.setCode(QMErrorCode.SUCCESS.getCode());
        goodsInfoSyncResponse.setMessage(QMErrorCode.SUCCESS.getMessage());
        goodsInfoSyncResponse.setItemId(ediGoodsSku.getId().toString());
        StringWriter sw = new StringWriter();
        JAXB.marshal(goodsInfoSyncResponse, sw);
        response.setResponseXml(sw.toString());
        return response;
    }
}
